package com.vincent.baseapp.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {

	public static String md516(String source, String charset) {
		MessageDigest md = null;

		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}

		md.reset();

		if (charset != null) {
			/* call the update method one or more times */

			/* (useful when you don't know the size of your data, eg. stream) */

			try {
				md.update(source.getBytes(charset));
			} catch (UnsupportedEncodingException e) {
				/* should not happen */
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}
		} else {
			md.update(source.getBytes());
		}

		/* now calculate the hash */

		byte[] encoded = md.digest();

		StringBuffer buf = new StringBuffer();

		for (int i = 0; i < encoded.length; i++) {
			if ((encoded[i] & 0xff) < 0x10) {
				buf.append("0");
			}

			buf.append(Long.toString(encoded[i] & 0xff, 16));
		}

		return buf.toString().substring(8, 24);
	}

	public static String md532(String source, String charset) {
		MessageDigest md = null;

		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}

		md.reset();

		if (charset != null) {
			/* call the update method one or more times */

			/* (useful when you don't know the size of your data, eg. stream) */

			try {
				md.update(source.getBytes(charset));
			} catch (UnsupportedEncodingException e) {
				/* should not happen */

				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}
		} else {
			md.update(source.getBytes());
		}

		/* now calculate the hash */

		byte[] encoded = md.digest();

		StringBuffer buf = new StringBuffer();

		for (int i = 0; i < encoded.length; i++) {
			if ((encoded[i] & 0xff) < 0x10) {
				buf.append("0");
			}

			buf.append(Long.toString(encoded[i] & 0xff, 16));
		}

		return buf.toString();
	}

	/**
	 * 获取字符串的MD5值 32位 用于远程注册码运算, cyj
	 */
	public static String md5(String plainText) {
		String md5str = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			/* 进行加密处理 */

			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			md5str = buf.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return md5str;
	}
}
